package com.erpoa.interceptor;

import com.erpoa.dto.DealMessage;
import com.erpoa.utils.AjaxResult;
import com.erpoa.utils.PDAException;
import com.erpoa.utils.ServletUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;


/**
 * @author chenjimin
 * @Title: GlobalExceptionHandler
 * @ProjectName oaerp
 * @Description: 全局异常处理
 * @date 2020/9/89:42
 */

@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    /**
     * 请求方式不支持
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public AjaxResult handleException(HttpRequestMethodNotSupportedException e) {
        log.error(e.getMessage(), e);
        return AjaxResult.error("不支持' " + e.getMethod() + "'请求");
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public AjaxResult notFount(RuntimeException e) {
        log.error("运行时异常:", e);
        return AjaxResult.error("运行时异常:" + e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e) {
        log.error(e.getMessage(), e);
        return AjaxResult.error("服务器错误，请联系管理员,错误信息" + e.getMessage());
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(PDAException.class)
    public Object PDAException(HttpServletRequest request, PDAException e) {
        log.error(e.getMessage(), e);
        if (ServletUtils.isAjaxRequest(request)) {
            return new DealMessage(false, e.getMessage());
        } else {
            return new DealMessage(false, e.getMessage());
        }
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public AjaxResult validatedBindException(BindException e) {
        log.error(e.getMessage(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return AjaxResult.error(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult MethodArgumentNotValidExceptio(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        String message = "未知";
        BindingResult bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
        // getFieldError获取的是第一个不合法的参数(P.S.如果有多个参数不合法的话)
        FieldError fieldError = bindingResult.getFieldError();
        if (fieldError != null) {
            message = fieldError.getDefaultMessage();
        }
        return AjaxResult.error(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(ValidationException.class)
    public AjaxResult ValidationException(ValidationException e) {
        log.error(e.getMessage(), e);
        String msg = "未知";
        if (e instanceof ConstraintViolationException) {
            msg = e.getMessage();
            if (msg != null) {
                int lastIndex = msg.lastIndexOf(':');
                if (lastIndex >= 0) {
                    msg = msg.substring(lastIndex + 1).trim();
                }
            }

        } else {
            msg = "处理参数时异常";
        }

        return AjaxResult.error(msg);
    }

}